from django import http
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE


class AreasView(View):
    def get(self,request):
        #省份 select * from tb_areas where parent_id is null;
        #市 select * from tb_areas where parent_id=130000 ;
        #县 select * from tb_areas where parent_id=130200 ;

        # 1接收参数 查询参数
        area_id = request.GET.get('area_id')
        # 2判断参数
        # 传进来的参数 area_id 没有值---省份
        if not area_id:
            #有缓存用缓存
            province_list = cache.get('province_list')
            if not province_list:


                provinces = Area.objects.filter(parent__isnull = True)

            #构建前端数据格式
                province_list = [{"id": pro.id, "name": pro.name} for pro in provinces]
                #存入缓存
                cache.set('province_list',province_list,3600)
            # for pro in provinces:
            #     data_dict = {
            #         "id":pro.id,
            #         "name":pro.name
            #     }
            # province_list.append(data_dict)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:
            sub_data = cache.get('sub_data_' + area_id)
            if not sub_data:
            # 有值--市和县
            #     subs = Area.objects.filter(parent_id = area_id)
            #     parent_model = Area.objects.get(id = area_id)

            #父级的内容
                parent_model = Area.objects.get(id=area_id)
            #根据父级获取市区
                subs = parent_model.subs.all()

            # 构建前端数据格式
                sub_list = [{"id": sub.id, "name": sub.name} for sub in subs]
                # for sub in subs:
                #     data_dict = {
                #         "id":sub.id,
                #         "name":sub.name
                #     }
                #     sub_list.append(data_dict)

                sub_data = {
                    'id':parent_model.id,
                    'name':parent_model.name,
                    'subs':sub_list
                }
                #存缓存
                cache.set('sub_data_' + area_id, sub_data, 3600)
        # 3返回结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})
